using System;
using System.Collections.Generic;
using System.Linq;
using ApiProject.Api.Data;
using ApiProject.Api.Entity;
using ApiProject.Api.PramaModel;
using ApiProject.Api.Repository;
using ApiProject.Api.Uitls;
using ApiProject.Api.Utils;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;


// 后台用户管理
namespace ApiProject.Api.Controllers
{
    // [Authorize]
    [ApiController]
    [Route("[controller]")]
    public class UserManageController : ControllerBase
    {
        private IRepository<Users> _usersRepository;

        private IRepository<UserInfo> _userInfoRepository;

        private Token _tokenParameter;

        private readonly IConfiguration _configuration;

        private readonly IWebHostEnvironment _hostingEnvironment;

        public UserManageController(
            IConfiguration configuration,
            IRepository<Users> usersRepository,
            IRepository<UserInfo> userInfoRepository,
            IWebHostEnvironment hostingEnvironment
        )
        {
            _usersRepository = usersRepository;
            _configuration = configuration;
            _userInfoRepository = userInfoRepository;
            _tokenParameter =
                _configuration.GetSection("TokenParameter").Get<Token>();
            _hostingEnvironment = hostingEnvironment;
        }

        // 后台管理系统 用户管理 分页显示用户列表
        // Get：/usermanage
        [HttpGet]
        public dynamic Get([FromQuery] Pages page)
        {
            var pageIndex = page.pageIndex;
            var pageSize = page.pageSize;

            // var users = _usersRepository.Table.Where(o =>o.IsDelete==false && o.IsEnable==true);

            var users = from user in _userInfoRepository.Table
                        join userInfo in _userInfoRepository.Table on user.Id equals userInfo.UserId
                        orderby user.Id
                        where user.IsDelete == false
                        select new { };


            var u = users.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();

            return JsonHelper.Serialize(new
            {
                Code = 200,
                Data = new { Data = u, pages = new { pageIndex, pageSize, rowsTotal = users.Count() } },
                Msg = "获取成功"
            });
        }

        //管理员修改用户信息
        // Put： /usermanage/{id}
        //参数：user的id user数据
        // [AllowAnonymous]
        [HttpPut("{id}")]
        public dynamic Put(int id, NewUser model)
        {
            var user = _usersRepository.GetById(id);
            if (user != null)
            {
                //修改user表的数据
                user.Username = model.Username;
                user.Remarks = model.Remarks;
                user.UpdatedTime = DateTime.Now;

                _usersRepository.Update(user);
                return JsonHelper.Serialize(new
                {
                    Code = 200,
                    Data = user,
                    Msg = string.Format("成功修改Id为{0}的用户", id)
                });
            }
            else
            {
                return JsonHelper.Serialize(new { Code = 1000, Data = "", Msg = "修改失败" });
            }
        }

        //伪删除用户
        // post /usermanage/delete 
        // 参数： user的id
        [HttpPost, Route("delete/{id}")]
        public dynamic IsDelete(int id)
        {
            var user = _usersRepository.GetById(id);

            if (user != null)
            {
                user.IsDelete = true;
                user.UpdatedTime = DateTime.Now;

                _usersRepository.Update(user);
                return JsonHelper.Serialize(new
                {
                    Code = 200,
                    Data = user,
                    Msg = string.Format("成功在表中删除Id为{0}的用户", id)
                });
            }
            else
            {
                return JsonHelper.Serialize(new { Code = 1000, Data = "", Msg = "删除失败" });
            }
        }


        //禁用用户
        // Post /usermanage/isenable/{id}
        // 参数 user的id
        [HttpPost, Route("isenable/{id}")]
        public dynamic IsEnable(int id)
        {
            var user = _usersRepository.GetById(id);
            Console.WriteLine(id);
            if (user != null)
            {
                user.IsEnable = false;
                user.UpdatedTime = DateTime.Now;
                _usersRepository.Update(user);
                return JsonHelper.Serialize(new
                {
                    Code = 200,
                    Data = user,
                    Msg = string.Format("已禁用Id为{0}的用户", id)
                });
            }
            else
            {
                return JsonHelper.Serialize(new { Code = 1000, Data = "", Msg = "禁用失败" });
            }
        }

        //模糊查询
        [HttpGet, Route("found")]
        public dynamic GetUser([FromQuery] Content model)
        {
            var str1 = model.cont.Trim();
            var str = str1.ToString();

            if (!string.IsNullOrEmpty(str) && str.GetType() == typeof(String))
            {

                var struser = _usersRepository.Table.Where(x => x.Username.Contains(str) || x.Remarks.Contains(str)).Where(o => o.IsDelete == false).ToList();

                var res = new
                {
                    Code = 1000,
                    Data = struser,
                    Msg = "成功✅"
                };

                return res;
            }
            else
            {
                return new
                {
                    Code = 400,
                    Data = "",
                    Msg = "传入应为字符串类型"
                };
            }
        }

        [HttpGet("{id}")]
        public dynamic Get(int id)
        {
            var users = _usersRepository.GetById(id);
            return users;
        }


        //添加用户
        [HttpPost]
        public dynamic Post(NewUser model)
        {
            var username = model.Username.Trim();
            var password = model.Password.Trim();
            var remarks = model.Remarks.Trim();
            if (string.IsNullOrEmpty(username))
            {
                var temp = new
                {
                    Code = 1000,
                    Data = "",
                    Msg = "用户名不能为空，请输入用户名"
                };
                return JsonHelper.Serialize(temp);
            }
            var user =
                new Users
                {
                    Username = username,
                    Password = password,
                    Remarks = remarks
                };
            _usersRepository.Insert(user);
            return JsonHelper.Serialize(new { Code = 200, Data = user, Msg = "创建用户成功" });
        }
       
        
    }
}
